package com.example.demoback.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demoback.common.Constants;
import com.example.demoback.common.Result;
import com.example.demoback.entity.Penalty;
import com.example.demoback.exception.ServiceException;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.example.demoback.service.ISeriousService;
import com.example.demoback.entity.Serious;
import com.example.demoback.entity.Serious1;
import com.example.demoback.service.ISerious1Service;

import org.springframework.web.multipart.MultipartFile;


import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyd
 * @since 2022-07-01
 */
@RestController
@RequestMapping("/serious")
public class SeriousController {

    //引入Service
    @Resource
    private ISeriousService seriousService;

    @Resource
    private ISerious1Service serious1Service;

    //新增或更新
    @PostMapping("/save")
    public Result save(@RequestBody Serious serious) {

        Boolean flag = false;
        //判断数据是否重复
            flag = seriousService.saveOrUpdate(serious);
            if (flag){
                Serious1 serious1 =new Serious1();
                BeanUtil.copyProperties(serious,serious1,true);
                if (!serious1Service.saveOrUpdate(serious1)){
                return Result.error1(false);
                }
            }
        else{
                return Result.error(false,"存在重复数据");
        }
        return Result.success(flag);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Serious serious) {

        Boolean flag = false;
        //判断数据是否重复
        int a ;
        a = getInfo(serious.getSeriousids());
        if (a == 1) {
            flag = seriousService.saveOrUpdate(serious);
            if (flag) {
                Serious1 serious1 = new Serious1();
                BeanUtil.copyProperties(serious, serious1, true);
                if (!serious1Service.saveOrUpdate(serious1)) {
                    return Result.error1(false);
                }
            }
        }else{
            return Result.error(false,"存在重复数据");
        }
        return Result.success(flag);
    }

    //根据id删除
    @DeleteMapping("/delete/{id}")  //通过“/user/”+id 的url调用接口
    public Result delete(@PathVariable Integer id) {
        Boolean flag = false;
        flag = seriousService.removeById(id);
        if (flag){
            if (!serious1Service.removeById(id)){
                return Result.error1(false);
            }
        }
        return Result.success(flag,"数据删除成功");
    }
    //批量删除
    @PostMapping("/delete/batch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids){
        return seriousService.removeByIds(ids);
    }

    //查询所有
    @GetMapping("/select/all")
    public Result findAll() {
        List<Serious> seriouss = seriousService.list();
        return Result.success(seriouss);
    }

    //根据id查询
    @GetMapping("select/{id}")
    public Result findOne(@PathVariable Integer id) {
        Serious serious = seriousService.getById(id);
        return Result.success(serious);
    }

    //分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String seriousids,//defaultValue = ""设置默认值为空
                                    @RequestParam(defaultValue = "") String seriousname) {

        Page<Serious> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Serious> querWrapper = new QueryWrapper<Serious>();
        if (!"".equals(seriousids)){
        querWrapper.like("seriousids",seriousids);//默认用and连接
        }
        if (!"".equals(seriousname)){
        querWrapper.like("seriousname",seriousname);//或连接为querWrapper.or().like
        }
        IPage<Serious> seriousIPage = seriousService.page(page,querWrapper);
        return Result.success(seriousIPage);
    }

    //导出excel表格
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查出所以数据
        List<Serious> list = seriousService.list();

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);//也可写为磁盘路径

        //自定义标题别名
        writer.addHeaderAlias("id", "严重失信信息id");
        writer.addHeaderAlias("seriousids", "统一社会信用代码");
        writer.addHeaderAlias("seriousname", "失信单位");
        writer.addHeaderAlias("seriousmakingdate", "做出决定时间");
        writer.addHeaderAlias("seriousremovaldate", "做出移出决定时间");
        writer.addHeaderAlias("seriousmakingauthority", "作出决定机关");
        writer.addHeaderAlias("seriousremovalauthority", "作出移出决定机关");
        writer.addHeaderAlias("seriousmakingreason", "列入严重失信原因");
        writer.addHeaderAlias("seriousremovalreason", "移出严重失信原因");

        writer.setColumnWidth(0,10);//0为第一列，列宽
        writer.setColumnWidth(1,25);//0为第一列，列宽
        writer.setColumnWidth(2,25);//0为第一列，列宽
        writer.setColumnWidth(3,25);
        writer.setColumnWidth(4,25);
        writer.setColumnWidth(5,25);
        writer.setColumnWidth(6,25);
        writer.setColumnWidth(7,35);
        writer.setColumnWidth(8,35);

        //设置所有单元格超过设置列间距自动换行
        StyleSet ss = writer.getStyleSet();
        ss.setWrapText();
        writer.setStyleSet(ss);


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("严重失信信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();//将数据刷新到输出流里面
        writer.flush(out, true);
        out.close();
        writer.close();
        }

    //excel表格导入数据
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {  //传入的属性名为file
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);//指定从第二行开始读
        List<Serious> seriouss = CollUtil.newArrayList();

        List<Serious1> serious1s = CollUtil.newArrayList();

        for (List<Object> row : list) {
            Serious serious = new  Serious();
    //            basic.setId(Integer.parseInt (row.get(0).toString())); //id为自增，无需导入
            serious.setSeriousids(row.get(0).toString());
            String key = row.get(0).toString();
            int a = getInfo(key);
            if (a != 1){
                continue;
            }
            serious.setSeriousname(row.get(1).toString());
            serious.setSeriousmakingdate(row.get(2).toString());
            serious.setSeriousremovaldate(row.get(3).toString());
            serious.setSeriousmakingauthority(row.get(4).toString());
            serious.setSeriousremovalauthority(row.get(5).toString());
            serious.setSeriousmakingreason(row.get(6).toString());
            serious.setSeriousremovalreason(row.get(7).toString());

            seriouss.add(serious);
        }


        Boolean flag = seriousService.saveBatch(seriouss);
        if (flag){
            for (List<Object> row : list) {
                Serious1 serious1 = new  Serious1();
        //            basic.setId(Integer.parseInt (row.get(0).toString())); //id为自增，无需导入
                serious1.setSeriousids(row.get(0).toString());
                String key = row.get(0).toString();
                int a = getInfo1(key);
                if (a != 1) {
                    continue;
                }
                serious1.setSeriousname(row.get(1).toString());
                serious1.setSeriousmakingdate(row.get(2).toString());
                serious1.setSeriousremovaldate(row.get(3).toString());
                serious1.setSeriousmakingauthority(row.get(4).toString());
                serious1.setSeriousremovalauthority(row.get(5).toString());
                serious1.setSeriousmakingreason(row.get(6).toString());
                serious1.setSeriousremovalreason(row.get(7).toString());
                serious1s.add(serious1);
            }
            if(!serious1Service.saveBatch(serious1s)){
            return Result.error1(false);
            }
        }

        return Result.success(flag,"数据批量导入成功");
        }

    public int getInfo(String key) {  //查询出一条数据
        QueryWrapper<Serious> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seriousids", key);
        int a = 2;
        Serious one = new Serious();
        try {
        one = seriousService.getOne(queryWrapper); // 从数据库查询信息
        } catch (Exception e) {
        a = 3;
        }
        if (one == null){
        a = 1;
        }
        return a; //1为不存在数据
        //2为存在一条数据
        //3为存在多条数据
        }

    //备用数据库查询
    public int getInfo1(String key) {  //查询出一条数据
        QueryWrapper<Serious1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seriousids", key);
        int a = 2;
        Serious1 one = new Serious1();
        try {
        one = serious1Service.getOne(queryWrapper); // 从数据库查询信息
        } catch (Exception e) {
        a = 3;
        }
        if (one == null){
        a = 1;
        }
        return a; //1为不存在数据
        //2为存在一条数据
        //3为存在多条数据
        }

    @GetMapping("/downloadPdf")
    public void downloadPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExportPdf(request, response);
    }

    /**
     * 文档排版
     */
    public void ExportPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/pdf");
        //下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=Serious.pdf");
        //设置中文
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);


        // 创建文件
        Document document = new Document();

        //设置修改器
        PdfWriter.getInstance(document, response.getOutputStream());
//        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(oldPath));
        // 打开文档
        document.open();
        //设置文档标题
        document.addTitle("PDF");
        //设置文档作者
        document.addAuthor("yyd");
        document.addCreationDate();
        //设置关键字
        document.addKeywords("iText");
        document.addLanguage("中文");
        //表头
        PdfPTable title = new PdfPTable(8);

        title.setWidthPercentage(100); // 宽度100%填充
//        title.setSpacingBefore(10f); // 前间距
//        title.setSpacingAfter(10f); // 后间距

        //设置列宽
        float[] columnWidths = {0.8f, 0.7f ,0.7f,0.5f,0.5f,0.5f,1.0f,1.0f};
        title.setWidths(columnWidths);
        PdfPCell cell;

//        title.HorizontalAlignment = 0;
//        title.TotalWidth = 500;//表格总宽度
//        title.LockedWidth = true;//锁定宽度
//        title.FixedHeight = height;
//        title.MinimumHeight = 36;//设置行高


        title.addCell(new Paragraph("统一社会信用代码", FontChinese));
        title.addCell(new Paragraph("失信单位", FontChinese));
        title.addCell(new Paragraph("做出决定时间", FontChinese));
        title.addCell(new Paragraph("做出移出决定时间", FontChinese));
        title.addCell(new Paragraph("作出决定机关", FontChinese));
        title.addCell(new Paragraph("作出移出决定机关", FontChinese));
        title.addCell(new Paragraph("列入严重失信原因", FontChinese));
        title.addCell(new Paragraph("移出严重失信原因", FontChinese));


        document.add(title);

        List<Serious> list = seriousService.list();
        for (Serious row : list) {
            //插入数据
            PdfPTable table = new PdfPTable(8);
            table.setWidthPercentage(100); // 宽度100%填充
            //设置列宽
            table.setWidths(columnWidths);

            table.addCell(new Paragraph(row.getSeriousids(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousname(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousmakingdate(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousremovaldate(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousmakingauthority(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousremovalauthority(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousmakingreason(), FontChinese));
            table.addCell(new Paragraph(row.getSeriousremovalreason(), FontChinese));


            document.add(table);
        }

        document.close();
    }


}

